<template>
  <el-dialog v-bind="$attrs" @close="handleClose" @open="handleOpen">
    <div class="m-center w-10/12">
      <el-form
        @submit.prevent.native
        label-width="150px"
        :model="form"
        ref="userForm"
        size='small'
        :rules="rules"
      >
        <el-form-item label="TOMS">
          <el-switch v-model="form.toms" :disabled="form.userId===''||(form.userId).length===0||form.userId===null">
          </el-switch>
        </el-form-item>
        <el-form-item
          :label="$t('system.user.organization') + ':'"
          prop="queryOrg"
        >
          <organization-select
            style="width: 100%"
            ref="organizationTree"
            :parent-org-id="orgId"
            :default-org-id="form.orgId"
            :auto-init="false"
            :list-data="orgs"
            :selectedOrg.sync="form.queryOrg"
          />
        </el-form-item>
        <el-form-item
          :label="$t('system.user.user_name') + ':'"
          prop="username"
        >
          <el-tooltip v-if="!usernameDisabled" placement="top">
            <div slot="content">{{ $t('system.user.email_tip') }}</div>
            <el-input
              maxlength="64"
              show-word-limit
              v-model="form.username"
              @blur="() => (form.username = form.username.trim())"
              :placeholder="$t('system.user.user_name')"
            ></el-input>
          </el-tooltip>
          <el-input
            v-if="usernameDisabled"
            :disabled="usernameDisabled"
            maxlength="64"
            show-word-limit
            v-model="form.username"
            @blur="() => (form.username = form.username.trim())"
            :placeholder="$t('system.user.user_name')"
          ></el-input>
        </el-form-item>

        <el-form-item :label="$t('system.user.name') + ':'" prop="name">
          <el-input
            maxlength="32"
            show-word-limit
            v-model="form.name"
            @blur="() => (form.name = form.name.trim())"
            :placeholder="$t('modules.tms.merchant.contact_name')"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.phone') + ':'" prop="mobile">
          <el-input
            maxlength="16"
            show-word-limit
            v-model="form.mobile"
            @blur="() => (form.mobile = form.mobile.trim())"
            :placeholder="$t('common.phone')"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('common.country_or_region') + ':'"
          prop="countryCode"
        >
          <el-select
            v-model="form.countryCode"
            filterable
            :placeholder="$t('common.country_or_region')"
            style="width: 100%"
          >
            <el-option
              v-for="item in countries"
              :key="item.countryCode3"
              :label="$t('country_or_region.' + item.countryCode3)"
              :value="item.countryCode3"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="this.form.userId"
          :label="$t('common.status') + ':'"
          prop="status"
        >
          <el-radio v-model="form.status" :label="1">{{
            $t('common.valid')
          }}</el-radio>
          <el-radio v-model="form.status" :label="0">{{
            $t('common.locked')
          }}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('system.user.role') + ':'" prop="roleIds">
          <el-checkbox-group
            v-if="roleData && roleData.length > 0"
            v-model="form.roleIds"
          >
            <el-checkbox
              v-for="role in roleData"
              :key="role.roleId"
              :label="role.roleId"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
          <div style="color: red" v-if="!this.form.userId">
            <el-button
              type="primary"
              @click="handleAddRole()"
              class="p-1.5 align-middle"
              size="small"
            >
              {{ $t('system.role.add_role') }}
            </el-button>
            <!--            {{ $t('system.user.no_role_tip0') }} <router-link :to="{path: '/role/index'}" style="text-decoration:underline">{{ $t('system.user.no_role_tip1' )}}</router-link> {{ $t('system.user.no_role_tip2' )}}-->
          </div>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">{{
        $t('page.cancel')
      }}</el-button>
      <el-button
        size="small"
        type="primary"
        :loading="confirmLoading"
        @click="saveUser()"
        >{{ $t('common.confirm') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { addUser, editUser, getUser, openTOMS, closeTOMS, getUserPlatform } from '@/api/user'
import { listRole } from '@/api/role'
import OrganizationSelect from '@/components/selects/organization-select'
import { checkPhoneNum } from '@/utils/validate'
export default {
  components: { OrganizationSelect },
  inheritAttrs: false,
  data() {
    return {
      confirmLoading: false,
      usernameDisabled: false,
      roleData: [],
      orgId: '',
      form: {
        toms: true,
        userId: '',
        queryOrg: {},
        createType: 0,
        orgId: '',
        username: '',
        name: '',
        email: '',
        mobile: '',
        countryCode: '',
        status: 1,
        roleList: [],
        roleIds: []
      },
      otherRoleIds: []
    }
  },
  computed: {
    ...mapGetters(['orgs', 'countries']),
    userNameRule() {
      if (this.form.userId) {
        return [
          {
            required: true,
            message: this.$t('common.message.please_input_account'),
            trigger: 'blur'
          }
        ]
      } else {
        return [
          {
            required: true,
            message: this.$t('common.message.please_input_account'),
            trigger: 'blur'
          },
          {
            type: 'email',
            message: this.$t('common.message.email_format_error'),
            trigger: 'blur'
          }
        ]
      }
    },
    rules() {
      var validateRole = (rule, value, callback) => {
        if (false == this.form.toms) {
          return callback()
        }
        if (!value || value.length == 0) {
          return callback(new Error(this.$t('common.message.please_select_role')))
        } else {
          return callback()
        }
      }
      return {
        queryOrg: [
          {
            required: true,
            message: this.$t('common.message.please_select_organization'),
            trigger: 'change'
          }
        ],
        username: this.userNameRule,
        name: [
          {
            required: true,
            message: this.$t('common.message.please_input_contact_name'),
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: this.$t('common.message.please_input_email'),
            trigger: 'blur'
          },
          {
            type: 'email',
            message: this.$t('common.message.email_format_error'),
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            validator: checkPhoneNum,
            trigger: 'blur'
          }
        ],
        countryCode: [
          {
            required: true,
            message: this.$t('common.message.please_select_country_region'),
            trigger: 'change'
          }
        ],
        status: [
          {
            required: true,
            message: this.$t('common.message.please_select_status'),
            trigger: 'change'
          }
        ],
        roleIds: [
          {
            required: true,
            validator: validateRole,
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    init(id) {
      this.form.userId = id
      if (id) {
        this.usernameDisabled = true
      } else {
        this.usernameDisabled = false
      }
      this.$nextTick(() => {
        this.$refs['userForm'].resetFields()
      })
    },
    handleClose() {
      // this.$nextTick(() => {
      //   this.$refs.organizationTree.reset()
      //
      // this.$refs['userForm'].resetFields()
      // this.form.queryOrg = {}
      // this.orgId = ''
      this.form.toms = true
      this.$emit('update:visible', false)
    },
    clear() {
      console.log('clear')
      this.$nextTick(() => {
        this.$refs.organizationTree.reset()
      })
      this.$refs['userForm'].resetFields()
      this.form.queryOrg = {}
      this.orgId = ''
    },
    handleAddRole() {
      this.$emit('update:visible', false)
      this.$emit('addRole')
    },
    saveUser() {
      if(false == this.form.toms){
        this.otherRoleIds.forEach(roleId => {
          if (!this.form.roleIds.find(item => item == roleId)) {
            this.form.roleIds.push(roleId)
          }
        })
      } else {
        let tmpRoleIds = []
        this.form.roleIds.forEach(roleId => {
          if (!this.otherRoleIds.find(item => item == roleId)) {
            tmpRoleIds.push(roleId)
          }
        })
        this.form.roleIds = tmpRoleIds
      }
      this.$refs['userForm'].validate((valid) => {
        if (valid) {
          if (this.form.roleIds.length > 5) {
            this.$message.error(this.$t('system.user.max_role_error'))
            return
          }
          this.confirmLoading = true
          //org
          this.form.orgId = this.form.queryOrg.orgId
          // role info
          this.form.roleList = []
          this.form.roleIds.forEach((roleId) => {
            this.form.roleList.push({ roleId: roleId })
          })
          if (this.form.userId) {
            //是否开通TOMS服务
            if (true == this.form.toms) {
              let data = {
                userId: this.form.userId,
                platCode: 'TOMS'
              }
              openTOMS(data).then((res) => {
                console.log(res)
              }).catch((e) => {
                this.$confirmError(e)
              })
              this.otherRoleIds.forEach(roleId => {
                if (!this.form.roleIds.find(item => item == roleId)) {
                  this.form.roleIds.push(roleId)
                }
                if (!this.form.roleList.find(item => item.roleId == roleId)) {
                  this.form.roleList.push({ roleId: roleId })
                }
              })
            } else {
              closeTOMS(this.form.userId).then((res) => {
                console.log(res)
              }).catch((e) => {
                this.$confirmError(e)
              })
            }
            editUser(this.form.userId, this.form)
              .then(() => {
                this.confirmLoading = false
                this.$message({
                  message: 'Update Success',
                  type: 'success'
                })
                this.$emit('submit')
                this.handleClose()
              })
              .catch((e) => {
                this.confirmLoading = false
                this.$confirmError(e)
              })
          } else {
            this.form.email = this.form.username
            this.form.contactName = this.form.name
            this.form.platCode = ['TOMS']
            addUser(this.form)
              .then(() => {
                this.confirmLoading = false
                this.$message({
                  message: 'Create Success',
                  type: 'success'
                })
                this.$emit('submit')
                this.handleClose()
              })
              .catch((e) => {
                this.confirmLoading = false
                this.$confirmError(e)
              })
          }
        } else {
          return false
        }
      })
    },
    handleOpen() {
      const userInfo = JSON.parse(
        localStorage.getItem(this.$store.getters.keys.storage.username)
      )
      this.orgId = String(userInfo.orgId)
      this.getAllRoles()
      if (this.form.userId) {
        // edit user
        this.getEditUserInfo(this.form.userId)
      } else {
        this.form.orgId = this.orgId
        this.$nextTick(() => {
          this.$refs.organizationTree.initData()
        })
      }
    },
    getEditUserInfo(userId) {
      let params = {
        userId: userId
      }
      this.form.toms = false
      getUserPlatform(params).then((res) => {
        for (let i = 0; i < res.length; i++) {
          if (res[i].platCode == 'TOMS') {
            this.form.toms = true
          }
        }
      }).catch((e) => {
        this.$confirmError(e)
      })
      getUser(userId)
        .then((res) => {
          // 改为打开弹窗的时候重置，因为close里面已经移除resetFields只关闭弹窗
          this.$refs['userForm'].resetFields()
          this.form.queryOrg = {}
          this.form.username = res.username
          this.form.orgId = res.orgId
          this.form.name = res.name
          this.form.email = res.email
          this.form.mobile = res.mobile
          this.form.countryCode = res.countryCode
          this.form.status = res.status
          if (res.roleList) {
            res.roleList.forEach((role) => {
              if (role.platCode.toUpperCase() == 'TOMS') {
                this.form.roleIds.push(role.roleId)
              } else {
                this.otherRoleIds.push(role.roleId)
              }
            })
          }
          this.$nextTick(() => {
            this.$refs.organizationTree.initData()
          })
        })
        .catch(this.$confirmError)
    },
    getAllRoles() {
      listRole({ platCode: 'TOMS' })
        .then((res) => {
          this.roleData = res
        })
        .catch(this.$confirmError)
    }
  },
  mounted() {}
}
</script>


<style lang="scss" scoped>
::v-deep .el-checkbox__label {
  vertical-align: middle;
  white-space: pre-line;
}
</style>
